//
//  ST_PairsShareParticularView.swift
//  btvideo
//
//  Created by mac on 2019/12/30.
//  Copyright © 2019 JarvanZhang. All rights reserved.
//

import UIKit
import KTVHTTPCache
import SnapKit
import SwifterSwift

protocol ST_PairsShareParticularViewDelegate:NSObjectProtocol {
    
    func PHScrollViewDidScroll(_ scrollView:UIScrollView,viewHeight:CGFloat)
    
    func PHScrollViewDidEndDecelerating(_ scrollView:UIScrollView)
    
}

class ST_PairsShareParticularView: UIScrollView {
    
//    默认创建最多的image个数
    static let max_image_count = 15
    
    /**
     默认静音
     */
    var isMuted = true{
        didSet{
            self.player?.isMuted = self.isMuted
        }
    }
//    瀑布流的位置
    var present_start_rect = CGRect.zero
    
    var present_start_idx:IndexPath?
    
    weak var fromeController:ST_PairsTransitionProtocol?
    
    weak var phDelegate:ST_PairsShareParticularViewDelegate?
    
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        
        
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        bounces = false
        
        showsHorizontalScrollIndicator = false
        showsVerticalScrollIndicator = false
        isPagingEnabled = true
        
        self.delegate = self
        
        self.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.equalTo(self.snp.width).multipliedBy(3)
            make.height.equalTo(self)
        }
        
        
        var lastImgView:UIImageView?
        
        for _ in 0 ... ST_PairsShareParticularView.max_image_count {
            
            let imgView = ST_PairsImageView.init(frame: CGRect.zero)
//            imgView.backgroundColor = UIColor.random
            imgView.contentMode = .scaleAspectFill
            imgView.clipsToBounds = true
            root_view.addSubview(imgView)
            
            imgView.snp.makeConstraints { (make) in
                if let last = lastImgView{
                    make.left.equalTo(last.snp.right)
                }else{
                    make.left.equalToSuperview()
                }
                make.width.height.equalTo(self)
                make.top.equalToSuperview()
            }
            
            imgView.preview_next_closure = {[weak self] in
                self?.scrollToNext()
            }
            
            imgView.preview_previous_closure = { [weak self] in
                self?.scrollToPrevious()
            }
            imgView.preview_curr_closure = {  [weak self] in
                self?.previewCurrentMedia()
            }
            
            lastImgView = imgView
        }
        
        
        
        add_notifications()
        
        /*
        self.addSubview(rightSignLabel)
        rightSignLabel.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize.init(width: 40, height: 22))
            make.left.equalToSuperview().offset(8)
            make.top.equalToSuperview().offset(8)
        }*/
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: - Properties
    /*
    lazy var rightSignLabel:UILabel = {
        let control = UILabel()
//        control.text = "新人"
        control.isHidden = true
        control.cornerRadius = 11
        control.textAlignment = .center
        control.textColor = UIColor.init(hex: 0x333333)
        control.backgroundColor = Color.white
        control.font = UIFont.systemFont(ofSize: 11, weight: UIFont.Weight.medium)
        return control
    }()*/
    
    fileprivate var root_view:UIView = {
       
        let control  = UIView()
        
//        let tap = UITapGestureRecognizer.init(target: self, action: #selector(display_full_image))
        
        return control
    }()
    
//    MARK: - Set UP Data
    func supplement(newArray:[ST_PairsShareParticularModel]){
        
//        只有一个不需要刷新
        if newArray.count < 2{
            return
        }
        
        
        for (idx,imageView) in (self.root_view.subviews as! [UIImageView]).enumerated() {
            
            if idx == 0{
                continue
            }
            
            if let m = newArray[safe:idx]{
                
                imageView.pin_setImage(from: m.imageUrl.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
                
                imageView.isHidden = false
            }else{
                imageView.isHidden = true
            }
        }
        
        
//        【更新宽度约束】
        root_view.snp.remakeConstraints { (make) in
            make.width.equalTo(self.snp.width).multipliedBy(newArray.count)
            make.edges.equalToSuperview()
            make.height.equalTo(self)
        }
        
        self.data_array = newArray
        
    }
    
    
    func setUp(data_array:[ST_PairsShareParticularModel]){
        
        self.setContentOffset(CGPoint.zero, animated: false)
        
        self.stop()
        
        if data_array.count < 1{
            return
        }
        
        self.data_array = data_array
        
        
        for (idx,imageView) in (self.root_view.subviews as! [UIImageView]).enumerated() {
            
            if let m = data_array[safe:idx]{
                
                
                imageView.pin_setImage(from: m.imageUrl.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
                
                imageView.isHidden = false
            }else{
                imageView.isHidden = true
            }
        }
        
        
//        【重写更新约束】
        root_view.snp.remakeConstraints { (make) in
            make.width.equalTo(self.snp.width).multipliedBy(data_array.count)
            make.edges.equalToSuperview()
            make.height.equalTo(self)
        }
        
        
        
//        print("【PH】centerScrollH---",centerScrollH)
        
        if let item = data_array.first , let url = item.videoUrl.url{
            self.currPalyIdx = 0
            self.play(url: url, duration: item.duration)
        }else{
            self.progress_closure?(1,0)
        }
        
    }
//    MARK: - Public Method
//    func roundCorners(cornerRadius: Double,allRoundCorner:Bool = true) {
//        
//        
//        return
//        
//        var corners:UIRectCorner = .allCorners
//        
//        if !allRoundCorner{
//            corners = [.topLeft,.topRight]
//        }
//        
//        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
//        
//        let maskLayer = CAShapeLayer()
//        maskLayer.frame = self.bounds
//        maskLayer.path = path.cgPath
//        self.layer.mask = maskLayer
//    }
    
    
    func refresh_data(){
        
        if self.contentOffset.x != 0 {
            
            clear_data()
            
            setUp(data_array: self.data_array)
            
        }
        
    }
    
    
    func clear_data(){
       
        self.stop()
        
        for (_,imageView) in (self.root_view.subviews as! [UIImageView]).enumerated() {
            
            imageView.isHidden = true
            imageView.image = nil
            
        }
//        self.rightSignLabel.isHidden = true
        self.contentOffset = CGPoint.zero
    }
    
    fileprivate(set) var data_array = [ST_PairsShareParticularModel]()
        
    //    MARK: -  player properties
    
    var progress_closure:((CGFloat,Int)->())?
    
    //    播放中
    var playing = false

    fileprivate var player:AVPlayer?

    fileprivate var time_observer:Any?

    fileprivate var playerItem:AVPlayerItem?

//    fileprivate var playerLayer:AVPlayerLayer?
    
    fileprivate var avPlayerView:ST_PairsAVPlayerView?
    
    fileprivate var currPalyIdx:Int?
    //    MARK: - private Method
    
    fileprivate func play(url:URL,duration:Int) {
     
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
        }catch{
            print("AVAudioSession.Category.playback Error")
        }
        
        guard let pUrl = KTVHTTPCache.proxyURL(withOriginalURL: url) else{
           print("缓存方案 创建代理Url失败：\(url)")
           return
        }
        
        let playerItem = AVPlayerItem(url: pUrl)
        
        self.playerItem = playerItem

        //创建ACplayer：负责视频播放
        self.player = AVPlayer.init(playerItem: playerItem)
        self.player?.isMuted = self.isMuted
        self.player?.rate = 1.0//播放速度 播放前设置
        //进度条
        let mainQueue = DispatchQueue.main
        
        // Invoke callback every second
        let interval = CMTime(seconds:1.0/20.0, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
        
        self.time_observer = self.player?.addPeriodicTimeObserver(forInterval: interval, queue: mainQueue, using: {[weak self] (time) in
                    
                let seconds = CMTimeGetSeconds(time)
                
                let d = duration < 1 ? 1 : duration
                 
                let percent = seconds/d.double
                
    //            print("当前播放的时间百分比:",percent)
                guard let strongSelf = self , let pIdx = strongSelf.currPalyIdx else{
                    return
                }
            
                strongSelf.progress_closure?(percent.cgFloat,pIdx)
            
        })
        
        
        //创建显示视频的图层
        avPlayerView = ST_PairsAVPlayerView()
        avPlayerView?.isUserInteractionEnabled = false
        self.addSubview(avPlayerView!)
        
//        avPlayerView?.backgroundColor = UIColor.red
        
        avPlayerView?.snp.makeConstraints({ (make) in
            make.edges.equalTo(self.root_view.subviews[currPalyIdx ?? 0])
        })
        
        guard let castedLayer = avPlayerView?.layer as? AVPlayerLayer else{
            return
        }
        
        castedLayer.player = self.player
        castedLayer.videoGravity = .resizeAspectFill
        
        guard let player = self.player else { return  }
        
        player.play()
        
        playing = true
        
    }
        
    fileprivate func stop(){
        
        playing = false
        
        currPalyIdx = nil
        
//        guard let playerLayer = self.playerLayer else { return  }
//        playerLayer.removeFromSuperlayer()
//        self.playerLayer = nil
        
        guard let player = self.player else { return  }
        
        if let ob = self.time_observer{
            player.removeTimeObserver(ob)
        }
        
        
        avPlayerView?.removeFromSuperview()
        avPlayerView = nil
        
        player.pause()
        
        self.player = nil
    }
    
    
}
//MARK: - ScrollView Delegate
extension ST_PairsShareParticularView:UIScrollViewDelegate{
    
    /*
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        currentOffset = scrollView.contentOffset.x
        
        self.contentSize = CGSize.init(width: ScreenWidth*imageViewCount.cgFloat, height: self.height)
        
        
    }*/
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let offsetY = scrollView.contentOffset.y
        
        let offset = scrollView.contentOffset.x
        
        if offsetY != 0{
            scrollView.contentOffset = CGPoint.init(x: offset, y: 0)
        }
        
        if offset < 0{
            return
        }
        
        let curr = offset.int/ScreenWidth.int
        
        guard let currItem = data_array[safe:curr] else{
            return
        }
        
        let dbl = offset/ScreenWidth
//        没有滑动
        if dbl.floor == dbl{
            
            let height = currItem.displayHeight
            
            self.phDelegate?.PHScrollViewDidScroll(scrollView, viewHeight: height)
            
            return
        }
        
        guard let nextItem = data_array[safe:curr+1] else {
            
            let height = currItem.displayHeight
            
            self.phDelegate?.PHScrollViewDidScroll(scrollView, viewHeight: height)
            
            return
        }
        
        let value = nextItem.displayHeight - currItem.displayHeight
        
        let scale = value/ScreenWidth
        
        let currOffset = offset - curr.cgFloat*ScreenWidth
        
//        self.size = CGSize.init(width: ScreenWidth, height: currItem.displayHeight+currOffset*scale)
        
        let height = currItem.displayHeight+currOffset*scale
        
        self.phDelegate?.PHScrollViewDidScroll(scrollView, viewHeight: height)
        
        
    }
    
    
//    MARK: Reuse Image View
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        
        scrollViewDidEndDecelerating(scrollView)
        
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        print("找到答案:scrollViewDidEndDecelerating")
        
        let currIdx = scrollView.contentOffset.x.int/ScreenWidth.int
     
        
        
        self.phDelegate?.PHScrollViewDidEndDecelerating(scrollView)
        
        guard let item = data_array[safe:currIdx] else{
            return
        }
        
        
        
        //        判断移除播放
        if let last = self.currPalyIdx {
            if  last != currIdx{
                self.stop()
                self.currPalyIdx = nil
                self.progress_closure?(1,currIdx)
                NotificationCenter.default.post(name: .personalVideoNeedPlay, object: nil)
            }
        }else{
            if let url = item.videoUrl.url{
                self.currPalyIdx = currIdx
                self.play(url: url, duration: item.duration)
                
                // 暂停小窗播放
                NotificationCenter.default.post(name: .personalVideoNeedPause, object: nil)
            }else{
                self.currPalyIdx = nil
                self.progress_closure?(1,currIdx)
                
                // 恢复小窗播放
                NotificationCenter.default.post(name: .personalVideoNeedPlay, object: nil)
            }
            
        }
        
        
        
        
        
        
        
    }
    
}

//MARK: - Public Method
extension ST_PairsShareParticularView{
    
    fileprivate func previewCurrentMedia(){
        
        let curr = (self.contentOffset.x/ScreenWidth).int
        
        var array = [ST_MWPhoto]()
        
        for model in data_array{
            
            guard let url = model.imageUrl.big_remote_image().url , let media = ST_MWPhoto.init(url: url) else{continue}
            
            array.append(media)
            
            if model.videoUrl.count < 3{
                continue
            }
            
            guard let videoUrl = model.videoUrl.url else { continue }
            
            media.videoURL = videoUrl
        }
        
        guard let browser = ST_MWPhotoBrowser.init(photos: array) else{
            return
        }
        browser.displayActionButton = false
        browser.setCurrentPhotoIndex(curr.uInt)
        
        let nav = UINavigationController.init(rootViewController: browser)
        
        GlobalPresent(toController: nav)
        
    }
    
    func scrollToNext()  {
        
        var curr = (self.contentOffset.x/ScreenWidth).int
        
        curr += 1
        
        if curr < self.data_array.count{
            
            self.setContentOffset(CGPoint.init(x: ScreenWidth*curr.cgFloat, y: 0), animated: true)
            
            self.progress_closure?(1,curr)
        }
        
    }
    
    func scrollToPrevious()  {
        
        var curr = (self.contentOffset.x/ScreenWidth).int
        
        curr -= 1
        
        if curr > -1{
            
            self.setContentOffset(CGPoint.init(x: ScreenWidth*curr.cgFloat, y: 0), animated: true)
            self.progress_closure?(1,curr)
        }
        
    }
}




//MARK: - Notification
extension ST_PairsShareParticularView{
    
    
    func add_notifications()  {
            
        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: .main) { [weak self] noti in
            
            if let playerItem = noti.object as? AVPlayerItem{
                
                if let currentItem = self?.player?.currentItem,playerItem == currentItem{
                    
//                    print("FWPlayer---播放完成，重新播放")
                    
                    self?.player?.seek(to: CMTime.zero)
                    self?.player?.play()
                    
                    return
                }
            }
        }
        
    }
}





//MARK: - Image Item
fileprivate class ST_PairsImageView: UIImageView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let nextVideoWidth = 100
        
        self.isUserInteractionEnabled = true
        
        self.addSubview(next_video_btn)
        self.addSubview(previous_video_btn)
        next_video_btn.snp.makeConstraints { (make) in
            make.bottom.right.top.equalToSuperview()
            make.width.equalTo(nextVideoWidth)
        }
        
        previous_video_btn.snp.makeConstraints { (make) in
            make.bottom.left.top.equalToSuperview()
            make.width.equalTo(nextVideoWidth)
        }
        
        self.addSubview(preview_btn)
        preview_btn.snp.makeConstraints { (make) in
            make.left.equalTo(previous_video_btn.snp.right)
            make.bottom.top.equalToSuperview()
            make.right.equalTo(next_video_btn.snp.left)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    fileprivate lazy var next_video_btn:UIButton = {
                   
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
//        control.backgroundColor = Color.init(white: 0, alpha: 0.2)
        
        control.addTarget(self, action: #selector(play_next_video), for: UIControl.Event.touchUpInside)
        
        return control
    }()

        
     fileprivate lazy var previous_video_btn:UIButton = {
       
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
//        control.backgroundColor = Color.init(white: 0, alpha: 0.2)
        
        control.addTarget(self, action: #selector(play_previous_video), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    fileprivate lazy var preview_btn:UIButton = {
           
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
//        control.backgroundColor = Color.init(white: 0, alpha: 0.2)
        
        control.addTarget(self, action: #selector(preview_curr_handle), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    var preview_next_closure:(()->())?
    
    var preview_previous_closure:(()->())?
    
    var preview_curr_closure:(()->())?
//    MARK: Event
    @objc fileprivate func play_next_video(){
        
        preview_next_closure?()
        
    }
    
    @objc fileprivate func play_previous_video(){
        
        preview_previous_closure?()
    }
    
    @objc fileprivate func preview_curr_handle(){
        
        preview_curr_closure?()
    }
    
}
